import { Injectable, Query, UnauthorizedException } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { UserService } from '../user/user.service'
// import { PermissionService } from '../permission/permission.service'

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
    // private permissionService: PermissionService,
  ) {}

  async signIn(username: string, password: string) {
    const user = await this.userService.findOneByUsername(username)

    if (user == void 0) {
      throw new UnauthorizedException('用户不存在！')
    } else if (user.password !== password) {
      // 密码错误
      throw new UnauthorizedException('密码错误！')
    }
    const access_token = this.jwtService.sign(
      { username: user.username, email: user.email },
      { expiresIn: '0.5h' },
    )
    const refresh_token = this.jwtService.sign(
      { username: user.username },
      { expiresIn: '7d' },
    )

    return {
      username: user.username,
      access_token,
      refresh_token,
    }
  }

  async refreshToken(@Query('token') token: string) {
    try {
      const data = this.jwtService.verify(token)
      const user = await this.userService.findOneByUsername(data.username)
      // const pers = await this.permissionService.findAll()

      const access_token = this.jwtService.sign(
        { username: user.username, email: user.email },
        { expiresIn: '0.5h' },
      )
      const refresh_token = this.jwtService.sign(
        { username: user.username },
        { expiresIn: '7d' },
      )
      return {
        userInfo: {
          username: user.username,
          access_token,
          refresh_token,
        },
        access_token,
        refresh_token,
      }
    } catch (e) {
      throw new UnauthorizedException('无效的token!请重新登入')
    }
  }
}
